//
//  investProjectViewController.m
//  HaoDeCaiFu
//
//  Created by 张玉鹏 on 2017/11/21.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "investProjectViewController.h"
#import "BAButton.h"
#import "makeUpTableViewCell.h"
#import "jijinAndGroupDetailModel.h"
#import "HDCFRedemptionPageVc.h"

#define kIHave @"/public/transaction/get-investor-holdings"


@interface investProjectViewController ()
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)NSArray*titleArray;

//是否可以赎回
@property (nonatomic, assign) BOOL isAvailableUnit;

@end

@implementation investProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isAvailableUnit = YES;
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.navigationController.navigationBarHidden=NO;

    
    self.title=self.titleStr;
    
    self.view.backgroundColor=ZKcolor(243, 243, 243);
    self.titleArray=@[@"投资成本",@"在途资产",@"累计收益(不含分红)",@"现金分红"];
    [self getMyPropertyList];
//    self.title=@"个别投资项目";
    
}




- (void)getMyPropertyList{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
     paramets[@"accountNumber"] = kAcount;
    if (self.zichanType==1) {
        
        if (self.code) {
          paramets[@"portfolioId"] = self.code;
        }
        
    }
    else
    {
        if (self.code) {
            paramets[@"fundCode"] = self.code;
        }
    }
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:kIHave};
    [SVProgressHUD show];
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary*resultDic=(NSDictionary*)result;
        NSString *code = resultDic[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary*dataDict=[resultDic objectForKey:@"data"];
            
            NSArray*dataArray=[dataDict objectForKey:@"data"];
            NSArray*dataArray1=[jijinAndGroupDetailModel mj_objectArrayWithKeyValuesArray:dataArray];
            if (dataArray1&&dataArray1.count!=0) {
                jijinAndGroupDetailModel*jijinModel=dataArray1[0];
                self.modelArray=jijinModel.fundHoldings.data;
                self.isShouhui=YES;
                for (jijinAndGroupDetailModel*model in jijinModel.fundHoldings.data) {
                    self.zichanXianzhiZong=[model.currentValue floatValue]+self.zichanXianzhiZong;
                    self.zuoriShouyiZong=[model.previousProfitLoss floatValue]+self.zuoriShouyiZong;
                    self.leijiShouyiZong=[model.profitLoss floatValue]+self.leijiShouyiZong;
                    self.touziChengbenZong=[model.investmentAmount floatValue]+self.touziChengbenZong;
                    self.xianjinFenhong=[model.dividendCash floatValue]+self.xianjinFenhong;
                     self.zaiTuZiChanZong=[model.intransitAssets floatValue]+self.zaiTuZiChanZong;
                    
                    self.keShuhuiJine=[model.nav floatValue]*[model.availableUnit floatValue]+self.keShuhuiJine;
                    
                    if ([model.sellEnable isEqualToString:@"N"]) {
                        self.isShouhui=NO;
                    }
                    jijinAndGroupDetailModel*mode111=jijinModel.fundHoldings.data.firstObject;
                    if ([model isEqual:mode111]) {
                        self.currentTime=model.navDate;
                    }
                    
                    if (self.zichanType!=1) {
                        self.shuhuiFenShu=model.availableUnit;
                    }
                }
                [self.tableView reloadData];
                [self.tableView setTableHeaderView:self.headerView];
                if (self.isShouhui==YES) {
                    [self configerBottomView];
                    _tableView.frame=CGRectMake(0, KNavHeight, screenWidth, screenHeight-49-KNavHeight);
                }
                else
                {
                    _tableView.frame=CGRectMake(0, KNavHeight, screenWidth, screenHeight-KNavHeight);
                }
                
                
            }
            
            
            [SVProgressHUD dismiss];
            
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];

            
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
    }];
    
}
- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

//时间戳转化为时间
-(NSString*)shijianChuoZhuanshijianWith:(NSString*)TimeStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[TimeStr doubleValue] / 1000];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;

}


-(void)configerBottomView
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, screenHeight - 49 , screenWidth, 49);
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitle:@"赎回" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(jumpBuy) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:ZKcolor(184, 27, 36)];
    [self.view addSubview:btn];
//    UIView*bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, screenHeight-49, screenWidth, 49)];
//    NSArray*array=@[@"赎回",@"吊舱",@"购买"];
//    for (NSInteger i=0; i<3; i++) {
//        UIButton*threeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//        threeBtn.frame=CGRectMake(screenWidth/3*i, 0, screenWidth/3, 49);
//        [threeBtn setTitle:array[i] forState:UIControlStateNormal];
////        [threeBtn setTintColor:[UIColor blueColor]];
//        [threeBtn setTitleColor:ZKcolor(198, 47, 47) forState:UIControlStateNormal];
//        threeBtn.layer.borderColor=ZKcolor(198, 47, 47).CGColor;
//        threeBtn.layer.borderWidth=0.6;
//        threeBtn.titleLabel.font=[UIFont systemFontOfSize:15];
//        [bottomView addSubview:threeBtn];
//    }
//    [self.view addSubview:bottomView];
}


-(void)jumpBuy
{

    
    if (self.keShuhuiJine<=0||!self.keShuhuiJine) {
        
        [SVProgressHUD showInfoWithStatus:@"没有可赎回的份额"];
        [SVProgressHUD dismissWithDelay:1];
        return;
        
    }

//    HDCFRedemptionPageVc*vc=[[HDCFRedemptionPageVc alloc]init];
//    vc.titleStr=self.titleStr;
//    vc.code=self.code;
//    vc.zichanType=self.zichanType;
//    vc.shuhuiFenShu=self.shuhuiFenShu;
//    vc.modelArray=self.modelArray;
//    vc.zichanXianzhiZong=self.keShuhuiJine;
//    vc.chargeMode=self.chargeMode;
//    [self.navigationController pushViewController:vc animated:YES];

    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您将使用奕丰金融提供的基金销售服务" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HDCFRedemptionPageVc*vc=[[HDCFRedemptionPageVc alloc]init];
        vc.titleStr=self.titleStr;
        vc.code=self.code;
        vc.zichanType=self.zichanType;
        vc.shuhuiFenShu=self.shuhuiFenShu;
        vc.modelArray=self.modelArray;
        vc.zichanXianzhiZong=self.keShuhuiJine;
        vc.chargeMode=self.chargeMode;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction: action1];
    [alert addAction: action2];
    [self presentViewController:alert animated:NO completion:nil];
    
    

}

-(UITableView*)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, KNavHeight, screenWidth, screenHeight-49-KNavHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor=ZKcolor(243, 243, 243);
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.sectionHeaderHeight=W_RATIO(100);
        _tableView.sectionFooterHeight=W_RATIO(30);
        [self.view addSubview: _tableView];
        
        [_tableView registerNib:[UINib nibWithNibName:@"makeUpTableViewCell" bundle:nil] forCellReuseIdentifier:@"makeUpTableViewCell"];
    }
    return _tableView;
}

-(UIView*)headerView
{
    if (!_headerView) {
        _headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, W_RATIO(340) + 30)];
        _headerView.backgroundColor=ZKcolor(243, 243, 243);
        UIView*whiteView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, W_RATIO(370))];
        whiteView.backgroundColor=[UIColor whiteColor];
        [_headerView addSubview:whiteView];
        
        UILabel*titleLable=[[UILabel alloc]initWithFrame:CGRectMake(0, W_RATIO(10) + 10, screenWidth, W_RATIO(60))];
        titleLable.text=@"资产现值(元)";
        titleLable.textAlignment=1;
        titleLable.font=[UIFont systemFontOfSize:15];
        titleLable.textColor=[UIColor lightGrayColor];
        [whiteView addSubview:titleLable];
        
        UILabel*valueLable=[[UILabel alloc]initWithFrame:CGRectMake(0,titleLable.bottom+W_RATIO(20), screenWidth, W_RATIO(80))];
        valueLable.text=[NSString stringWithFormat:@"%.2f",self.zichanXianzhiZong];
        valueLable.font=[UIFont systemFontOfSize:20];
        valueLable.textAlignment=1;
        valueLable.textColor=COLOR_NAV;
        [whiteView addSubview:valueLable];
        
//        UILabel*timeLable=[[UILabel alloc]initWithFrame:CGRectMake(0,valueLable.bottom+W_RATIO(10), screenWidth, W_RATIO(60))];
//        if (self.currentTime) {
//            timeLable.text=[self shijianChuoZhuanshijianWith:self.currentTime];
//        }
//        else
//        {
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            [formatter setDateStyle:NSDateFormatterMediumStyle];
//            [formatter setTimeStyle:NSDateFormatterShortStyle];
//            [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//            timeLable.text=[formatter stringFromDate:[NSDate date]];
//        }
//        
//        timeLable.textAlignment=1;
//        timeLable.font=[UIFont systemFontOfSize:13];
//        timeLable.textColor=[UIColor lightGrayColor];
//        [whiteView addSubview:timeLable];
        
        UIView*lineView=[[UIView alloc]initWithFrame:CGRectMake(0, valueLable.bottom + 20, screenWidth, 0.6)];
        lineView.backgroundColor=[UIColor lightGrayColor];
        [whiteView addSubview:lineView];
        
        UIButton*lastoday=[UIButton buttonWithType:UIButtonTypeCustom];
        lastoday.frame=CGRectMake(0, lineView.bottom+W_RATIO(20), screenWidth/2-0.3, W_RATIO(40));
        [lastoday setTitle:[NSString stringWithFormat:@"%.2f",self.zuoriShouyiZong] forState:UIControlStateNormal];
        [lastoday setTitleColor:COLOR_NAV forState:UIControlStateNormal];
        lastoday.titleLabel.font=[UIFont systemFontOfSize:14];
        if (self.zuoriShouyiZong>0) {
            [lastoday setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
        }
        else if (self.zuoriShouyiZong<0)
        {
            [lastoday setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
        }
        lastoday.ba_buttonLayoutType=BAKit_ButtonLayoutTypeCenterImageRight;
        lastoday.ba_padding=3;
        [whiteView addSubview:lastoday];
        
        UILabel*lastdayLable=[[UILabel alloc]initWithFrame:CGRectMake(0,lastoday.bottom, lastoday.width, W_RATIO(40))];
        lastdayLable.text=@"昨日收益(元)";
        lastdayLable.textAlignment=1;
        lastdayLable.font=[UIFont systemFontOfSize:13];
        lastdayLable.textColor=[UIColor lightGrayColor];
        [whiteView addSubview:lastdayLable];
        
        UIView*shuLine=[[UIView alloc]initWithFrame:CGRectMake(lastoday.width,lineView.bottom+W_RATIO(30), 0.6, W_RATIO(60))];
        shuLine.backgroundColor=[UIColor lightGrayColor];
        [whiteView addSubview:shuLine];
        
        UIButton*leijiBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        leijiBtn.frame=CGRectMake(shuLine.right, lineView.bottom+W_RATIO(20), screenWidth/2, W_RATIO(40));
        [leijiBtn setTitle:[NSString stringWithFormat:@"%.2f",self.leijiShouyiZong] forState:UIControlStateNormal];
        [leijiBtn setTitleColor:COLOR_NAV forState:UIControlStateNormal];
        leijiBtn.titleLabel.font=[UIFont systemFontOfSize:14];
        leijiBtn.ba_buttonLayoutType=BAKit_ButtonLayoutTypeCenterImageRight;
        leijiBtn.ba_padding=8;
        if (self.leijiShouyiZong>0) {
          [leijiBtn setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
        }
        else if (self.leijiShouyiZong<0)
        {
            [leijiBtn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
        }
        
        [whiteView addSubview:leijiBtn];
        
//        UILabel*baifenLable=[[UILabel alloc]initWithFrame:CGRectMake(leijiBtn.right,leijiBtn.top, leijiBtn.width, W_RATIO(40))];
//        baifenLable.text=@"0.02%";
//        baifenLable.textAlignment=0;
//        baifenLable.font=[UIFont systemFontOfSize:13];
//        baifenLable.textColor=COLOR_NAV;
//        [whiteView addSubview:baifenLable];
        
        
        UILabel*leijiLable=[[UILabel alloc]initWithFrame:CGRectMake(shuLine.right,lastoday.bottom, lastoday.width, W_RATIO(40))];
        leijiLable.text=@"累计收益(元)";
        leijiLable.textAlignment=1;
        leijiLable.font=[UIFont systemFontOfSize:13];
        leijiLable.textColor=[UIColor lightGrayColor];
        [whiteView addSubview:leijiLable];


        
    }
    return _headerView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 4;
    }
    else
    {
        return self.modelArray.count;
    }
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return W_RATIO(100);
}

-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
    return W_RATIO(30);
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray*titleArray=@[@"资产概述",@"组合明细"];
    
    UIView*headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, W_RATIO(100))];
    headView.backgroundColor=[UIColor whiteColor];
    
    
    UIButton*titlebtn=[UIButton buttonWithType:UIButtonTypeCustom];
    titlebtn.frame=CGRectMake(W_RATIO(20), 0, screenWidth-W_RATIO(60), W_RATIO(100));
     [titlebtn setImage:[UIImage imageNamed:@"icon_zc"] forState:UIControlStateNormal];
    [titlebtn setTitle:titleArray[section] forState:UIControlStateNormal];
    [titlebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    titlebtn.titleLabel.font=[UIFont systemFontOfSize:15];
    titlebtn.ba_buttonLayoutType=BAKit_ButtonLayoutTypeLeftImageLeft;
    titlebtn.ba_padding=3;
    [headView addSubview:titlebtn];
    
    UIView*lineView=[[UIView alloc]initWithFrame:CGRectMake(0, headView.bottom-0.6, screenWidth, 0.6)];
    lineView.backgroundColor=ZKcolor(243, 243, 243);
    [headView addSubview:lineView];
    
    return headView;
  
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return W_RATIO(100);
    }
    else
    {
        return 75;
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, W_RATIO(30))];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==1) {
        makeUpTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"makeUpTableViewCell" forIndexPath:indexPath];
        jijinAndGroupDetailModel*model=self.modelArray[indexPath.row];
        
        cell.name.text=model.fundName;
        cell.shouyi.text=[NSString stringWithFormat:@"%@元",model.currentValue];
        cell.numStyle.text=[NSString stringWithFormat:@"%@ %@",model.fundCode,model.mainCode];
        cell.zhanbi.text=[NSString stringWithFormat:@"%.2f%%",[model.currentValue floatValue]/self.zichanXianzhiZong*100];
        cell.zhanbi.textColor=[UIColor lightGrayColor];

        return cell;
    }
    
    static NSString *cellIdentifier=@"Cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    else
    {
        for (UIView*view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
    }
    
    
    
    
    if (indexPath.section==0) {
         UILabel*titleLable=[[UILabel alloc]initWithFrame:CGRectMake(W_RATIO(30), 0, screenWidth/2-W_RATIO(30), W_RATIO(100))];
        titleLable.font=[UIFont systemFontOfSize:15];
        [cell.contentView addSubview:titleLable];
        
        
        UILabel*valueLable=[[UILabel alloc]initWithFrame:CGRectMake(screenWidth/2, 0, screenWidth/2-W_RATIO(30), W_RATIO(100))];
        valueLable.font=[UIFont systemFontOfSize:15];
        valueLable.textAlignment=2;
        if (indexPath.row==0) {
            titleLable.text=self.titleArray[indexPath.row];
//
            valueLable.text=[NSString stringWithFormat:@"%.2f元",self.touziChengbenZong];
        }
        else if (indexPath.row==1)
        {
            
            titleLable.text=self.titleArray[indexPath.row];
           
            valueLable.text=[NSString stringWithFormat:@"%.2f元", self.zaiTuZiChanZong];
            
            
        }
        else if (indexPath.row==2)
        {
            NSString *agreeStr = self.titleArray[2];
            NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:agreeStr];
            NSRange range = [agreeStr rangeOfString:@"(不含分红)"];
            [AttributedStr addAttribute:NSFontAttributeName
                                  value:[UIFont systemFontOfSize:15]
                                  range:range];
            
            [AttributedStr addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor lightGrayColor]
                                  range:range];
            valueLable.textColor=COLOR_NAV;
            titleLable.attributedText=AttributedStr;
            valueLable.text=[NSString stringWithFormat:@"%.2f元",self.leijiShouyiZong-self.xianjinFenhong];
           
            
        }
        else
        {
            valueLable.text=[NSString stringWithFormat:@"%.2f元",self.xianjinFenhong];
            titleLable.text=self.titleArray[indexPath.row];
        }
         [cell.contentView addSubview:valueLable];

        
        
        
    }
    
    
    
    return cell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
